import { Toast } from 'antd-mobile'
import { createAction, NavigationActions, Storage, URL } from '../utils'
import { post } from '../utils/fetch'

export default {
  namespace: 'signUp',
  state: {
    loading: true,
    token: null,
    username: null,
    password: null
  },
  reducers: {
    updateState(state, { payload }) {
      return { ...state, ...payload }
    },
    addToken(state, { payload }) {
      return {
        ...state,
        token: {
          ...payload.sessionToken
        }
      }
    },
    addUsers(state, { payload }) {
      return {
        ...state,
        ...payload
      }
    }
  },
  effects: {
    * loadSignUp(action, { call, put }) {
      yield put(createAction('updateState')({ loading: false }))
    },
    * SignUp({ payload }, { call, put }) {
      try {
        const { username, password } = payload
        const data = yield call(() => post(`${URL}1/users`, payload))
        if (data) {
          yield put(createAction('addToken')({ token: data }))
          yield put(createAction('addUsers')({ username, password }))
          yield put(NavigationActions.navigate({ routeName: 'Login' }))
          Toast.info('注册成功', 1)
        } else {
          Toast.info('输入账号密码有误！！！', 1)
        }
      } catch (e) {
        console.log(e);
      }
    }
  },
  subscriptions: {
    setup({ dispatch }) {
      dispatch({ type: 'loadSignUp' })
    }
  }
}
